/* Copyright 2007-2008 dnAnalytics Project.
 *
 * Contributors to this file:
 * Patrick van der Velde
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 * 
 * * Redistributions of source code must retain the above copyright notice, this 
 *   list of conditions and the following disclaimer.
 * * Redistributions in binary form must reproduce the above copyright notice, 
 *   this list of conditions and the following disclaimer in the documentation
 *   and/or other materials provided with the distribution.
 * * Neither the name of the dnAnalytics Project nor the names of its contributors
 *   may be used to endorse or promote products derived from this software without
 *   specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

using System;
using System.Diagnostics;

namespace dnAnalytics.LinearAlgebra.Solvers
{
    /// <summary>
    /// Defines an <see cref="IIterationStopCriterium"/> that monitors the numbers of iteration 
    /// steps as stop criterium.
    /// </summary>
    public sealed class IterationCountStopCriterium : IIterationStopCriterium
    {
        /// <summary>
        /// The default value for the maximum number of iterations the process is allowed
        /// to perform.
        /// </summary>
        private const int s_DefaultMaximumIterations = 1000;

        /// <summary>
        /// The default status.
        /// </summary>
        private static readonly ICalculationStatus s_DefaultStatus = new CalculationIndetermined();

        /// <summary>
        /// Returns the default value for the maximum number of iterations.
        /// </summary>
        public static int DefaultMaximumNumberOfIterations
        {
            get
            {
                return s_DefaultMaximumIterations;
            }
        }

        /// <summary>
        /// The maximum number of iterations the calculation is allowed to perform.
        /// </summary>
        private int m_MaximumNumberOfIterations;

        /// <summary>
        /// The status of the calculation
        /// </summary>
        private ICalculationStatus m_Status = s_DefaultStatus;

        /// <summary>
        /// Creates an instance of the <c>IterationStopCriterium</c> class with the default maximum 
        /// number of iterations.
        /// </summary>
        public IterationCountStopCriterium()
            : this(s_DefaultMaximumIterations)
        { }

        /// <summary>
        /// Creates an instance of the <c>IterationStopCriterium</c> class with the specified maximum
        /// number of iterations.
        /// </summary>
        /// <param name="maximumNumberOfIterations">
        ///   The maximum number of iterations the calculation is allowed to perform.
        /// </param>
        public IterationCountStopCriterium(int maximumNumberOfIterations)
        {
            if (maximumNumberOfIterations < 1)
            {
                throw new ArgumentOutOfRangeException("maximumNumberOfIterations");
            }

            m_MaximumNumberOfIterations = maximumNumberOfIterations;
        }

        /// <summary>
        /// Gets or sets the maximum number of iterations the calculation is allowed to perform.
        /// </summary>
        /// <exception cref="ArgumentOutOfRangeException">Thrown if the <c>Maximum</c> is set to a negative value.</exception>
        public int MaximumNumberOfIterations
        {
            [DebuggerStepThrough]
            get
            {
                return m_MaximumNumberOfIterations;
            }
            [DebuggerStepThrough]
            set
            {
                if (value < 1)
                {
                    throw new ArgumentOutOfRangeException("value");
                }

                m_MaximumNumberOfIterations = value;
            }
        }

        /// <summary>
        /// Returns the maximum number of iterations to the default.
        /// </summary>
        public void ResetMaximumNumberOfIterationsToDefault()
        {
            m_MaximumNumberOfIterations = s_DefaultMaximumIterations;
        }

        /// <summary>
        /// Determines the status of the iterative calculation based on the stop criteria stored
        /// by the current <c>IIterationStopCriterium</c>.
        /// </summary>
        /// <param name="iterationNumber">The number of iterations that have passed so far.</param>
        /// <param name="solutionVector">The vector containing the current solution values.</param>
        /// <param name="sourceVector">The right hand side vector.</param>
        /// <param name="residualVector">The vector containing the current residual vectors.</param>
        /// <returns>
        ///   An <c>ICalculationStatus</c> which indicates what the status of the iterative 
        ///   calculation is according to the current <c>IIterationStopCriterium</c>.
        /// </returns>
        /// <remarks>
        /// The individual stop criteria may internally track the progress of the calculation based
        /// on the invocation of this method. Therefore this method should only be called if the 
        /// calculation has moved forwards at least one step.
        /// </remarks>
        public void DetermineStatus(int iterationNumber, Vector solutionVector, Vector sourceVector, Vector residualVector)
        {
            if (iterationNumber < 0)
            {
                throw new ArgumentOutOfRangeException("iterationNumber");
            }

            if (iterationNumber >= m_MaximumNumberOfIterations)
            {
                SetStatusToFinished();
            }
            else
            {
                SetStatusToRunning();
            }
        }

        private void SetStatusToFinished()
        {
            if (!(m_Status is CalculationStoppedWithoutConvergence))
            {
                m_Status = new CalculationStoppedWithoutConvergence();
            }
        }

        private void SetStatusToRunning()
        {
            if (!(m_Status is CalculationRunning))
            {
                m_Status = new CalculationRunning();
            }
        }

        /// <summary>
        /// Returns the current calculation status.
        /// </summary>
        public ICalculationStatus Status
        {
            [DebuggerStepThrough]
            get
            {
                return m_Status;
            }
        }

        /// <summary>
        /// Resets the <c>IIterationStopCriterium</c> to the pre-calculation state.
        /// </summary>
        public void ResetToPrecalculationState()
        {
            m_Status = s_DefaultStatus;
        }

        /// <summary>
        /// Returns the <c>StopLevel</c> which indicates what sort of stop criterium this
        /// <c>IIterationStopCriterium</c> monitors.
        /// </summary>
        /// <value>Returns <see cref="dnAnalytics.LinearAlgebra.Solvers.StopLevel.StoppedWithoutConvergence"/>.</value>
        public StopLevel StopLevel
        {
            [DebuggerStepThrough]
            get
            {
                return StopLevel.StoppedWithoutConvergence;
            }
        }

        /// <summary>
        /// Clones the current <c>IterationCountStopCriterium</c> and its settings.
        /// </summary>
        /// <returns>A new instance of the <c>IterationCountStopCriterium</c> class.</returns>
        public IIterationStopCriterium Clone()
        {
            return new IterationCountStopCriterium(m_MaximumNumberOfIterations);
        }

        object ICloneable.Clone()
        {
            return Clone();
        }
    }
}
